#include "Encoding.h"

int32 Encoding::GetString( cbyte* bytes , cuint32 byteSize , string& value )
{
	tchar* dstString = new tchar[byteSize];
	if(dstString == 0)
		return E_ENCODING_ALLOC_BUFFER;
	int32 code = R_SUCCEED;

	uint32 useByteSize = 0;
	uint32 useCharSize = 0;
	code = Decode(bytes , byteSize , dstString , byteSize , useCharSize , useByteSize );
	if(code == R_SUCCEED)
		value.assign( dstString , useCharSize );

	delete[] dstString;

	return code;
}

int32 Encoding::GetBytes( cstring& value , byte* bytes , cuint32 byteSize )
{
	uint32 useByteSize = 0;
	uint32 useCharSize = 0;
	return Encode( value.c_str() , (uint32)value.size() , bytes , byteSize , useByteSize , useCharSize );
}

Encoding* Encoding::Create( EncodingType encodings )
{
	Encoding* encoding = 0;

	switch( encodings )
	{
	case ENCODING_UNICODE:
		encoding = new UnicodeEncoding();
		break;
	case ENCODING_UTF8:
		encoding = new UTF8Encoding();
		break;
	case ENCODING_GB2312:
		encoding = new DBCSEncoding( CODE_PAGE_GB2312 );
		break;
	default:
		break;
	}
	return encoding;
}

void Encoding::Destroy( Encoding* encoding )
{
	delete encoding;
}

int32 Encoding::GetMaxCharSize( cuint32& byteSize , uint32& charSize )
{
	uint32 uCharSize = 0;
	int32  code      = R_SUCCEED;

	code = GetCharSize( uCharSize );

	if(code != R_SUCCEED)
		return code;

	charSize = byteSize * uCharSize;

	return code;
}

int32 Encoding::GetMaxByteSize( cuint32& charSize , uint32 byteSize )
{
	uint32 uByteSize = 0;
	int32  code      = R_SUCCEED;

	code = GetByteSize( uByteSize );

	if( code != R_SUCCEED )
		return code;

	byteSize = uByteSize * charSize;

	return code;
}